/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package io.simple.core;

import com.google.common.io.ByteStreams;
import injections.Injector;
import injections.JSONSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @author Tom
 */
public class Bootstrap {

    private static final Logger LOGGER = LoggerFactory.getLogger(Bootstrap.class);

    public static void main(String[] args) throws Exception {
        if (args.length != 1) {
            System.out.println("Use 1 argument - path to JSON config file");
            System.exit(-1);
        }
        run(args[0]);
    }

    public static void run(String bootstrapConfigPath) throws Exception {
        try {
            LOGGER.info("Starting server, using config path " + bootstrapConfigPath);
            InputStream in = new FileInputStream(bootstrapConfigPath);
            String json = new String(ByteStreams.toByteArray(in), "UTF-8");
            JSONSource src = new JSONSource(json);
            Injector inj = new Injector(src.get());
            Object obj = inj.injectRoot();
            if (obj instanceof Server) {
                Server server = (Server) obj;
                server.start();
            } else {
                throw new IllegalArgumentException("Unknown server instance " + obj.getClass());
            }
            LOGGER.info("Server running...");
        } catch (Throwable t) {
            LOGGER.error("Error initializing server!", t);
            System.exit(78);
        }
    }

}
